//
//  NSAttributedString+YHExtension.swift
//  Adorbee
//
//  Created by amovision on 2024/11/26.
//

import UIKit

public extension AString {
  convenience init(_ text: Any?, font: UIFont, color: UIColor) {
    if let text = text as? AString {
      self.init(attributedString: text)
    } else {
      self.init(string: text as? String ?? "", attributes: [.font: font, .foregroundColor: color])
    }
  }

  var width: CGFloat {
    let font = attributes?[NSAttributedString.Key.font.rawValue] as? UIFont ?? UIFont.systemFont(ofSize: 17)
    return string.size(for: [.font: font]).width
  }

  func height(_ width: CGFloat) -> CGFloat {
    let font = attributes?[NSAttributedString.Key.font.rawValue] as? UIFont ?? UIFont.systemFont(ofSize: 17)
    return string.size(for: [.font: font], size: CGSizeMake(width, .infinity)).height
  }

  static func string(with strings: [AString]) -> Self {
    let mstr = MAString()
    strings.forEach { mstr.append($0) }
    return mstr.copy() as! Self
  }

  static func strings(_ titles: Any, fonts: Any, colors: Any) -> [AString] {
    let ts: [Any] = if let v = titles as? [String] { v }
    else if let v = titles as? String { [v] }
    else if let v = titles as? AString { [v] }
    else { fatalError("title error") }
    let fs = if let v = fonts as? [UIFont] { v }
    else if let v = fonts as? UIFont { [v] }
    else { fatalError("font error") }
    let cs = if let v = colors as? [UIColor] { v }
    else if let v = colors as? UIColor { [v] }
    else { fatalError("color error") }
    let maxCount = [ts.count, fs.count, cs.count].max()!
    var strings = [AString]()
    for idx in 0 ..< maxCount {
      let t = ts[min(idx, ts.count-1)]
      let f = fs[min(idx, fs.count-1)]
      let c = cs[min(idx, cs.count-1)]
      strings.append(AString(t, font: f, color: c))
    }
    return strings
  }
}
